<template>
  <div>
    <div style="width: 40%;margin-bottom: 12px" class="flex-row">
      <input ref="ipt" v-model="queryGoods.keyword" class="ipt">
      <el-button type="primary" @click="queryGoods01">搜索</el-button>
    </div>
    <vue-context-menu
      :context-menu-data="contextMenuData"
      @tableConfig="tableConfig"
      @deletedata="deletedata"
      @removeStorage="removeStorage"
    />
    <div v-if="showPromotionBox && promotionList.length" class="suspensionBox">
      <div class="close flex flex-reverse" @click="showPromotionBox = false">×</div>
      <div class="title flex a-item j-content">促销列表</div>
      <div>
        <div v-for="item in promotionList" class="promotion flex a-item" @dblclick.stop="setPromotionId(item)">
          {{ item.promotionName }}
        </div>
      </div>
    </div>
    <!-- 表格配置 -->
    <el-dialog
      title="表格配置"
      :visible.sync="tableConfigShow01"
      append-to-body
      width="60%"
    >
      <j-table-column-config :columns.sync="header" @tabSave="tabSave" @pit="pit" />
    </el-dialog>
    <el-dialog
      v-dialogDrag
      title="促销"
      :visible.sync="promotionShow"
      append-to-body
      width="1600px"
    >
      <div v-if="promotionGoodsList.length" class="promotionType flex flex-row">
        <div class="fl1" style="width: 800px">促销类型:{{ promotionName }}</div><div class="fl1">剩余可赠数量:{{ giveCount }}</div>
      </div>
      <div v-if="promotionGoodsList.length" class="rightTableBox flex flex-row">
        <div class="fl1"><el-table
          ref="promotionTable"
          height="555"
          :data="promotionGoodsList"
          border
          highlight-current-row="highlight-current-row"
          current-change="currentChange"
          style="width: 100%"
          @header-dragend="changeColWidth"
          @contextmenu.native="showMenu"
          @sort-change="sortTab"
        >
          <el-table-column prop="goodsName" width="300px" label="活动商品名称" />
          <el-table-column prop="barcode" width="100px" label="条形码" />
          <el-table-column prop="goodsCount" width="200px" label="辅数量">
            <template slot-scope="scope">
              <div class="flex flex-row">
                <div class="inputBox flex flex-row fl1">
                  <input
                    v-model="scope.row.boxNum"
                    oninput="value=parseInt(value.replace(/[^\d]+/g,''))"
                    maxlength="12"
                    type="number"
                    @change="computedCount(scope.row,'boxNum',scope.$index)"
                  >
                  <div style="height: 100%;font-size: 15px;color: black" class="flex a-item j-content">{{ scope.row.boxUnitName }}</div>
                </div>
                <div class="inputBox flex flex-row fl1">
                  <input
                    v-model="scope.row.mainNum"
                    oninput="value=parseInt(value.replace(/[^\d]+/g,''))"
                    maxlength="12"
                    type="number"
                    @change="computedCount(scope.row,'mainNum')"
                  >
                  <div style="height: 100%;font-size: 15px;color: black" class="flex a-item j-content">{{ scope.row.mainUnitName }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table></div>
        <div class="fl1"><el-table
          ref="giftTble"
          height="555"
          :data="giftList"
          border
          highlight-current-row="highlight-current-row"
          current-change="currentChange"
          style="width: 100%"
          @header-dragend="changeColWidth"
          @contextmenu.native="showMenu"
          @sort-change="sortTab"
        >
          <el-table-column prop="goodsName" width="300px" label="赠品名称" />
          <el-table-column prop="barcode" width="100px" label="条形码" />
          <el-table-column prop="goodsCount" width="200px" label="辅数量">
            <template slot-scope="scope">
              <div class="flex flex-row">
                <div class="inputBox flex flex-row fl1">
                  <input
                    v-model="scope.row.boxNum"
                    oninput="value=parseInt(value.replace(/[^\d]+/g,''))"
                    maxlength="12"
                    type="number"
                    @change="computedCount(scope.row,'boxNum')"
                  >
                  <div style="height: 100%;font-size: 15px;color: black" class="flex a-item j-content">{{ scope.row.boxUnitName }}</div>
                </div>
                <div class="inputBox flex flex-row fl1">
                  <input
                    v-model="scope.row.mainNum"
                    oninput="value=parseInt(value.replace(/[^\d]+/g,''))"
                    maxlength="12"
                    type="number"
                    @change="computedCount(scope.row,'mainNum')"
                  >
                  <div style="height: 100%;font-size: 15px;color: black" class="flex a-item j-content">{{ scope.row.mainUnitName }}</div>
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table></div>

      </div>
      <div class="bottomBtn" style="width: 100%">
        <el-button type="primary" class="btn_1" @click="promotionShow = false">取消</el-button>
        <el-button type="primary" class="btn_1" @click="pushGoods">确定</el-button>
      </div>
    </el-dialog>
    <div class="tabBox">
      <div class="flex flex-row">
        <div class="leftTableBox"><el-table
          ref="table"
          height="555"
          :data="goodsList"
          border
          highlight-current-row="highlight-current-row"
          current-change="currentChange"
          style="width: 100%"
          @row-click="setGoods"
          @row-dblclick="pushGoods"
          @header-dragend="changeColWidth"
          @contextmenu.native="showMenu"
          @sort-change="sortTab"
        >
          <el-table-column
            v-for="(item, index) in header"
            v-if="item.visible"
            :key="`col_${index}`"
            :prop="item.prop"
            :label="columnLabel(item)"
            :width="item.width + 'px'"
            :data-porp="item.prop"
            :sortable="item.sortable?'custom':false"
            @contextmenu.native="showMenu"
            @header-dragend="changeColWidth"
          >
            <!-- 自定义渲染模版 -->
            <template slot-scope="scope">
              <span v-if="item.type == 1" style="margin-left: 10px">{{ scope.row[`${item.prop}`] }}</span>
              <span v-else-if="item.type == 2" style="margin-left: 10px">{{ parseTime(scope.row[`${item.prop}`]) }}</span>
              <span v-else-if="item.type == 3" style="margin-left: 10px">{{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}</span>
              <span v-else-if="item.type == 4" >
                <span v-if="item.prop === 'usableNum'" :ref="'ref'+scope.$index">
                  {{ computedNum(scope.row) }}
                </span>
                <span v-else-if="item.prop === 'goodsName'" :ref="'ref'+scope.$index">
                  <div v-if="scope.row.giftPromotionInfoList" class="promotionTypeName">满赠</div>{{ scope.row.goodsName }}
                </span>
              </span>
            </template>
          </el-table-column>
        </el-table></div>
      </div>
      <div class="flex flex-row">
        <div style="width: 70%">
          <el-pagination
            :current-page.sync="query.page"
            :page-sizes="[10,20,50, 100]"
            :page-size="query.size"
            layout="sizes, prev, pager, next"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        <div class="bottomBtn">
          <el-button type="primary" class="btn_1" @click="closeDialog">取消</el-button>
          <el-button type="primary" class="btn_1" @click="pushGoods">确定</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>

import { getGoods } from '@/api/erp/basGoods'
import { queryGoods } from '@/utils/key'
import { basGoodsListForAddWithGiftPromotion } from '@/api/erp/salesOrder'
import { tablemixins } from '@/mixins/tablemixins'
import jTableColumnConfig from '@/components/jTableColumnConfig/jTableColumnConfig'
import Sortable from 'sortablejs'
import { giftPromotionDetail } from '@/api/erp/salesOrder'
import Vue from 'vue'
import { paperGoodsWithEmptyBoxGoodsList } from '../../api/erp/salesOrder'
import { v4 as uuidv4 } from 'uuid'
export default {
  name: 'JGoodsSelect',
  components: { jTableColumnConfig },
  mixins: [queryGoods, tablemixins],
  props: {
    queryGoods: {
      type: Object,
      default: null
    },
    showQueryGoods: {
      type: Boolean,
      default: false
    },
    type: {
      type: String
    },
    params:{
      type: Object,
      default: {}
    },
    customerId: {
      type: [String, Number]
    },
    buyChannel: {
      type: [String, Number],
      default: ''
    },
    noReturnBox: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      query: {
        page: 1,
        size: 20,
        sort: 'goodsCode,asc'
      },
      promotionId: null,
      promotionCode: null,
      promotionName: null,
      suspensionBoxTop: 0,
      ignoreGoodsTagNames: '',
      tableConfigShow01: false,
      goodsList: [],
      showPromotionBox: true,
      total: 0,
      promotionList: [
      ],
      giveCount: 0,
      promotionShow: false,
      giftList: [],
      promotionGoodsList: [],
      filterList: [],
      header: [
        {
          'dictionary': '',
          'label': '商品编码',
          'prop': 'goodsCode',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 200
        },
        {
          'dictionary': '',
          'label': '商品名称',
          'prop': 'goodsName',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 500
        },
        {
          'dictionary': '',
          'label': '条形码',
          'prop': 'barcode',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 200
        },
        {
          'dictionary': '',
          'label': '箱条码',
          'prop': 'boxBarcode',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 200
        },
        {
          'dictionary': '',
          'label': '规格',
          'prop': 'model',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 200
        },
        {
          'dictionary': '',
          'label': '可用量',
          'prop': 'usableNum',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 200
        },
        {
          'dictionary': '',
          'label': '可用辅数量',
          'prop': 'usableNum',
          'showName': '',
          'type': '4',
          'visible': true,
          'width': 200
        },
        {
          'dictionary': '',
          'label': '单价',
          'prop': 'taxPrice',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 150
        },
        {
          'dictionary': '',
          'label': '箱价',
          'prop': 'taxBoxPrice',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 150
        }
      ],
      remark: '',
      contextMenuData: {
        menuName: 'table1',
        axis: {
          x: null,
          y: null
        },
        promotionName: '',
        // 菜单选项
        menulists: [{
          fnHandler: 'tableConfig', // 绑定事件
          icoName: 'el-icon-setting', // icon图标
          btnName: '表格设置' // 菜单名称
        }, {
          fnHandler: 'removeStorage', // 绑定事件
          icoName: 'el-icon-delete', // icon图标
          btnName: '清除缓存' // 菜单名称
        }
        ]
      },
      ruleList: []
    }
  },
  computed: {
  },
  activated() {
    this.onGet()
  },
  created() {
    const header = JSON.parse(localStorage.getItem('jGoodsSelect'))
    this.header = header || this.header
    if (this.noReturnBox) {
      this.queryGoods.ignoreGoodsTagNames = '回瓶回箱,瓶盖'
    } else {
      this.queryGoods.ignoreGoodsTagNames = ''
    }

    this.onGet()
  },
  mounted() {
    // this.$refs.ipt.focus()
  },
  methods: {
    queryInit() {
      this.query.page = 1
      this.query.size = 50
      this.goodsList = []
    },
    queryGoods01() {
      this.query.page = 1
      this.onGet()
    },
    onGet() {
      this.giftList = []
      this.promotionGoodsList = []
      basGoodsListForAddWithGiftPromotion({ ...this.query, ...this.queryGoods, type: this.type, customerId: this.customerId, buyChannel: this.buyChannel,...this.params }).then(res => {
        this.goodsList = res.content
        this.total = res.totalElements
        this.$refs.table.setCurrentRow(this.goodsList[0])
        setTimeout(() => {
          this.promotionList = this.$refs.table.store.states.currentRow.giftPromotionInfoList || []
        }
        , 100)
      })
    },
    getGiftCount(isGift) {
      if (!this.promotionGoodsList) {
        return
      }
      const promotionGoodsList = this.promotionGoodsList.filter(item => item.goodsCount > 0)
      // 获取活动商品箱数
      let promotionBoxCount = 0
      // 获取赠品数量
      let promotionCount = 0
      promotionGoodsList.forEach(item => {
        promotionCount += Number(item.goodsCount)
        promotionBoxCount += Number(item.boxNum)
      })
      const giftList = this.giftList.filter(item => item.goodsCount > 0)
      // 获取赠品箱数
      let giftBoxCount = 0
      // 获取赠品数量
      let giftCount = 0
      giftList.forEach(item => {
        giftCount += Number(item.goodsCount)
        giftBoxCount += Number(item.boxNum)
      })
      // 判断活动商品满赠类型
      if (this.ruleList[0].reachType === 2) {
        // 阶梯过滤出当前促销符合的条件
        const satisfyList = this.ruleList.filter(item => item.full <= promotionCount)
        // 查询最大符合条件
        let satisfy = null
        satisfyList.forEach(item => {
          if (!satisfy || item.full > satisfy.full) {
            satisfy = item
          }
        })
        console.log(satisfy)
        // 符合促销
        if (satisfy) {
          // 计算最大满足倍数
          const promotionNum = parseInt(promotionCount / satisfy.full)
          // 计算最大赠送赠品数量
          const giftNum = promotionNum * satisfy.result
          // 判断当前赠品数量是否超最大可赠送数量
          if (this.giftList.length === 1 && !isGift) {
            if (satisfy.resultType === 2) {
              this.giftList[0].goodsCount = giftNum
              const boxCount = parseInt(Number(this.giftList[0].goodsCount) / Number(this.giftList[0].boxUnitCount))
              this.giftList[0].mainNum = Number(this.giftList[0].goodsCount) % Number(this.giftList[0].goodsCount.boxUnitCount)
              this.giftList[0].boxNum = boxCount
            } else {
              this.giftList[0].goodsCount = giftNum * this.giftList[0].boxUnitCount
              this.giftList[0].mainNum = 0
              this.giftList[0].boxNum = giftNum
            }
            return `0${satisfy.resultType === 2 ? '瓶' : '箱'}`
          }
          return `${giftNum - (satisfy.resultType === 2 ? giftCount : giftBoxCount)}${satisfy.resultType === 2 ? '瓶' : '箱'}`
        } else {
          return '0瓶'
        }
      } else if (this.ruleList[0].reachType === 3) {
        // 阶梯过滤出当前促销符合的条件
        const satisfyList = this.ruleList.filter(item => item.full <= promotionBoxCount)
        // 查询最大符合条件
        let satisfy = null
        satisfyList.forEach(item => {
          if (!satisfy || item.full > satisfy.full) {
            satisfy = item
          }
        })
        // 符合促销
        if (satisfy) {
          // 计算最大满足倍数
          const promotionNum = parseInt(promotionBoxCount / satisfy.full)
          // 计算最大赠送赠品数量
          const giftNum = promotionNum * satisfy.result
          console.log(`活动商品箱数${promotionBoxCount},满促条件${satisfy.full},单次满足可赠为${promotionNum},满足可赠箱数${giftNum}`)
          // 判断当前赠品数量是否超最大可赠送数量
          // 判断赠品类型
          if (this.giftList.length === 1 && !isGift) {
            if (satisfy.resultType === 2) {
              this.giftList[0].goodsCount = giftNum
              const boxCount = parseInt(Number(this.giftList[0].goodsCount) / Number(this.giftList[0].boxUnitCount))
              this.giftList[0].mainNum = Number(this.giftList[0].goodsCount) % Number(this.giftList[0].goodsCount.boxUnitCount)
              this.giftList[0].boxNum = boxCount
            } else {
              this.giftList[0].goodsCount = giftNum * this.giftList[0].boxUnitCount
              this.giftList[0].mainNum = 0
              this.giftList[0].boxNum = giftNum
            }
            return `0${satisfy.resultType === 2 ? '瓶' : '箱'}`
          }
          return `${giftNum - (satisfy.resultType === 2 ? giftCount : giftBoxCount)}${satisfy.resultType === 2 ? '瓶' : '箱'}`
        } else {
          return '0瓶'
        }
      }
    },
    computedNum(goods) {
      const boxCount = parseInt(goods.usableNum / Number(goods.boxUnitCount))
      const mainCount = goods.usableNum % Number(goods.boxUnitCount)
      return `${boxCount}${goods.boxUnitName}${mainCount}${goods.mainUnitName}`
    },
    pushGoods() {
      if (this.promotionGoodsList.length === 0) {
        const currentRow = this.$refs.table.store.states.currentRow
        // if (currentRow.giftPromotionInfoList){
        //   currentRow.giftPromotionInfoList.length === 1 && this.setPromotionId(currentRow.giftPromotionInfoList[0])
        //   currentRow.giftPromotionInfoList.length > 1 && this.$message.error('请先选择促销')
        //   return
        // }
        this.$emit('diaLogGoodsChange', { data: currentRow, row: this.$parent.$parent.$refs.table.store.states.currentRow, index: this.queryGoods.index })
      } else {
        const isRequiredList = this.promotionGoodsList.filter(item => item.isRequired == '1')
        const requiredGoods = []
        for (let i of isRequiredList){
          if (i.isRequired == '1' && !i.goodsCount){
            requiredGoods.push(i.goodsName)
          }
        }
        if (requiredGoods.length){
          this.$message.error(`${requiredGoods.join(',')}为必输商品，请检查`)
          return
        }
        // if(!isRequiredList.every(item=>item.goodsCount)) return
        const promotionGoodsList = this.promotionGoodsList.filter(item => item.goodsCount > 0)
        // 获取活动商品箱数
        let promotionBoxCount = 0
        // 获取赠品数量
        let promotionCount = 0
        promotionGoodsList.forEach(item => {
          promotionCount += Number(item.goodsCount)
          promotionBoxCount += Number(item.boxNum)
        })
        const giftList = this.giftList.filter(item => item.goodsCount > 0)
        // 获取赠品箱数
        let giftBoxCount = 0
        // 获取赠品数量
        let giftCount = 0
        giftList.forEach(item => {
          giftCount += Number(item.goodsCount)
          giftBoxCount += Number(item.boxNum)
        })
        // 判断活动商品满赠类型
        if (this.ruleList[0].reachType === 2) {
          // 阶梯过滤出当前促销符合的条件
          const satisfyList = this.ruleList.filter(item => item.full <= promotionCount)
          // 查询最大符合条件
          let satisfy = null
          satisfyList.forEach(item => {
            if (!satisfy || item.full > satisfy.full) {
              satisfy = item
            }
          })
          // 符合促销
          if (satisfy) {
            // 计算最大满足倍数
            const promotionNum = parseInt(promotionCount / satisfy.full)
            // 计算最大赠送赠品数量
            const giftNum = promotionNum * satisfy.result
            // 判断当前赠品数量是否超最大可赠送数量
            // 判断赠品类型
            if (satisfy.resultType === 2) {
              if (giftCount > giftNum) {
                this.$message.error(`当前赠品数量大于可赠送数量，不允许下单;可赠数量为${giftNum}瓶，当前赠送数量为${giftCount}瓶`)
              } else if (giftCount < giftNum) {
                this.$confirm('当前赠品数量小于可赠送数量, 是否下单?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  this.addPromotionList()
                }).catch(() => {
                  return
                })
              } else if (giftCount === giftNum) {
                this.addPromotionList()
              }
            } else if (satisfy.resultType === 3) {
              // 判断当前赠品数量是否超最大可赠送数量
              const mainGift = this.giftList.find(item => item.mainNum > 0)
              if (mainGift) {
                this.$message.error('赠送规格为箱,不允许输入零数')
                return
              }
              if (giftBoxCount > giftNum) {
                this.$message.error(`当前赠品数量大于可赠送数量，不允许下单;可赠数量为${giftNum}箱，当前赠送数量为${giftBoxCount}箱`)
              } else if (giftBoxCount < giftNum) {
                this.$confirm('当前赠品数量小于可赠送数量, 是否下单?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  this.addPromotionList()
                }).catch(() => {
                  return
                })
              } else if (giftBoxCount === giftNum) {
                this.addPromotionList()
              }
            }
          } else {
              this.$confirm('当前活动商品数量不满足促销条件, 是否下单?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.$emit('addPromotionList', { data: promotionGoodsList, index: this.queryGoods.index })
              }).catch(() => {

              })
          }
        } else if (this.ruleList[0].reachType === 3) {
          // 阶梯过滤出当前促销符合的条件
          const satisfyList = this.ruleList.filter(item => item.full <= promotionBoxCount)
          // 查询最大符合条件
          let satisfy = null
          satisfyList.forEach(item => {
            if (!satisfy || item.full > satisfy.full) {
              satisfy = item
            }
          })
          console.log(satisfy)
          // 符合促销
          if (satisfy) {
          // 计算最大满足倍数

            const promotionNum = parseInt(promotionBoxCount / satisfy.full)
            // 计算最大赠送赠品数量
            const giftNum = promotionNum * satisfy.result
            console.log(`活动商品箱数${promotionBoxCount},满促条件${satisfy.full},单词满足可赠为${promotionNum},满足可赠箱数${giftNum}`)
            // 判断当前赠品数量是否超最大可赠送数量
            // 判断赠品类型

            if (satisfy.resultType === 2) {
              if (giftCount > giftNum) {
                this.$message.error(`当前赠品数量大于可赠送数量，不允许下单;可赠数量为${giftNum}瓶，当前赠送数量为${giftCount}瓶`)
              } else if (giftCount < giftNum) {
                this.$confirm('当前赠品数量小于可赠送数量, 是否下单?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  this.addPromotionList()
                }).catch(() => {
                  return
                })
              } else if (giftCount === giftNum) {
                this.addPromotionList()
              }
            } else if (satisfy.resultType === 3) {
            // 判断当前赠品数量是否超最大可赠送数量
              const mainGift = this.giftList.find(item => item.mainNum > 0)
              if (mainGift) {
                this.$message.error('赠送规格为箱,不允许输入零数')
                return
              }
              if (giftBoxCount > giftNum) {
                this.$message.error(`当前赠品数量大于可赠送数量，不允许下单;可赠数量为${giftNum}箱，当前赠送数量为${giftBoxCount}箱`)
              } else if (giftBoxCount < giftNum) {
                this.$confirm('当前赠品数量小于可赠送数量, 是否下单?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
                }).then(() => {
                  this.addPromotionList()
                }).catch(() => {

                })
              } else if (giftBoxCount === giftNum) {
                this.addPromotionList()
              }
            }
          } else {
              this.$confirm('当前活动商品数量不满足促销条件,是否下单', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.$emit('addPromotionList', { data: promotionGoodsList, index: this.queryGoods.index })
              }).catch(() => {

              })
          }
        }
      }
    },
    // 提交并添加空箱
    async addPromotionList() {
      const date = new Date().getTime()
      const giftList = this.giftList.filter(item => item.goodsCount > 0)
      const promotionList = this.promotionGoodsList.filter(item => item.goodsCount > 0)
      const giftEmptyBoxList = giftList.filter(item => item.packageType == 1 && item.isGiftPaperBox == 0)
      const goodsIds = giftEmptyBoxList.map(item => item.goodsId).join(',')
      // const emptyBoxList = []
      if (goodsIds) {
        const { content } = await paperGoodsWithEmptyBoxGoodsList({ ids: goodsIds, customerId: this.customerId })
        for (const i of content) {
          const gift = this.giftList.find(item => item.goodsId === i.id)
          if (!gift) {
            continue
          }

          const uuid = `${date}${gift.goodsId}`
          const emptyBox = i.paperEmptyBoxGoodsInfo
          if (!emptyBox) {
            continue
          }
          emptyBox.boxNum = Number(gift.boxNum)
          emptyBox.mainNum = 0
          emptyBox.goodsCount = emptyBox.boxNum * Number(emptyBox.boxUnitCount)
          emptyBox.billTaxPrice = emptyBox.billTaxPrice || emptyBox.taxPrice
          emptyBox.billTaxBoxPrice = emptyBox.billTaxBoxPrice || emptyBox.taxBoxPrice
          emptyBox.taxAmount = emptyBox.goodsCount * emptyBox.taxPrice
          emptyBox.billTaxAmount = emptyBox.billTaxPrice * emptyBox.goodsCount
          emptyBox.boxCount = emptyBox.boxNum
          emptyBox.isEmptyBoxAdd = '1'
          emptyBox.sourceDetailType = '1'
          emptyBox.isPromotionAdd = '0'
          gift.promotionEmptyBoxKey = uuid
          emptyBox.promotionEmptyBoxKey = uuid
          emptyBox.promotionId = this.promotionId
          emptyBox.promotionCode = this.promotionCode
          emptyBox.promotionName = this.promotionName
          const index = this.giftList.indexOf(gift)
          giftList.splice(index + 1, 0, emptyBox)
          // emptyBoxList.push(emptyBox)
        }
      }
      const promotionGoodsList = [...promotionList, ...giftList]
      for (const i of promotionGoodsList) {
        i.promotionGroupKey = date
        i.remark = this.remark
        i.isPromotion = 1
        i.isOne =  0
        i.promotionId = this.promotionId
        i.promotionType = '3'
        i.promotionCode = this.promotionCode
        i.promotionName = this.promotionName
        i.sourceDetailType = i.isEmptyBoxAdd?'1':'2'
      }
      if (promotionList.length ===1 && giftList.filter(item=>item.isEmptyBoxAdd !== '1').length === 1){
        const promotionGoods = promotionGoodsList[0]
        promotionGoods.promotionData = {}
        promotionGoods.promotionData.gift = promotionGoodsList[1]
        promotionGoods.promotionData.ruleList = this.ruleList
        promotionGoods.isOne = 1
        promotionGoods.promotionData.emptyBox = promotionGoodsList[2]
        promotionGoods.promotionData = JSON.stringify(promotionList[0].promotionData)
      }
      this.$emit('addPromotionList', { data: promotionGoodsList, index: this.queryGoods.index })
    },
    handleCurrentChange(val) {
      this.query.page = val
      this.onGet()
    },
    handleSizeChange(val) {
      this.query.size = val
      this.onGet()
    },
    closeDialog() {
      this.$emit('closeDialog', '1')
    },
    setGoods(val) {
      if (!this.showPromotionBox) {
        this.showPromotionBox = true
      }
      setTimeout(() => {
        this.giftList = []
        this.promotionGoodsList = []
        this.promotionList = this.$refs.table.store.states.currentRow.giftPromotionInfoList || []
      }
      , 10)
    },
    showMenu() {
      event.preventDefault()
      var x = event.clientX
      var y = event.clientY
      // Get the current location
      this.contextMenuData.axis = {
        x, y
      }
    },
    tableConfig() {
      this.tableConfigShow01 = true
    },
    deletedata() {
    },
    toUpdateHeader() {
      console.log(this.header)
      localStorage.setItem('jGoodsSelect', JSON.stringify(this.header))
    },
    pit() {
      this.toUpdateHeader()
      this.handleCancelSort()
    },
    initSortable() {
      const th = this
      const el = document.querySelector('.tabBox .el-table__header-wrapper thead tr')
      // 创建拖拽对象
      new Sortable(el, {
        onEnd(evt) {
          const { newIndex, oldIndex, item } = evt
          // 获取原来title的name
          const oldtitle = item.children[0].innerHTML
          let thOldIndex = -1
          // 根据name获取所在的索引
          for (let i = 0; i < th.header.length; i++) {
            if (th.header[i].showName === oldtitle) {
              thOldIndex = i
              break
            }
          }
          // 获取隐藏后的数组
          const list = th.header.filter(item => item.visible === true)
          // 获取新位置所在的name值
          const newtitle = list[newIndex].showName
          // 根据name获取所在的索引
          let thNewIndex = -1
          for (let i = 0; i < th.header.length; i++) {
            if (th.header[i].showName === newtitle) {
              thNewIndex = i
              break
            }
          }

          const temp = th.header[thOldIndex]
          if (temp === null || temp === undefined) {
            return
          }
          th.header.splice(thOldIndex, 1)
          th.header.splice(thNewIndex, 0, temp)
          th.toUpdateHeader()
          th.handleCancelSort()
        }
      })
    },
    handleCancelSort() {
      // 使table先隐藏，再显示，table将恢复拖拽之前的样式
      this.isShowTable = false
      setTimeout(() => {
        this.isShowTable = true
        // 必须延时，否则重新初始化的sortable无法拖拽
        setTimeout(() => {
          this.initSortable()
        }, 500)
      }, 100)
    },
    getDict(str) {
      return eval(str)
    },
    removeStorage() {
      localStorage.removeItem('jGoodsSelect')
      this.header = [
        {
          'dictionary': '',
          'label': '商品编码',
          'prop': 'goodsCode',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 150
        },
        {
          'dictionary': '',
          'label': '商品名称',
          'prop': 'goodsName',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 200
        },
        {
          'dictionary': '',
          'label': '条形码',
          'prop': 'barcode',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 100
        }, {
          'dictionary': '',
          'label': '可用量',
          'prop': 'usableNum',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '可用辅数量',
          'prop': 'usableNum',
          'showName': '',
          'type': '4',
          'visible': true,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '单价',
          'prop': 'taxPrice',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 100
        },
        {
          'dictionary': '',
          'label': '箱价',
          'prop': 'taxBoxPrice',
          'showName': '',
          'type': '1',
          'visible': true,
          'width': 100
        }
      ]
    },
    changeColWidth(nw, ow, col, evt) {
      const list = this.header
      list.map((res, i) => {
        if (res.label.indexOf(col.label) !== -1) {
          this.header[i].width = nw
        }
      })
      this.toUpdateHeader()
    },
    computedCount(row, type, index) {
      if (type === 'boxNum') {
        row.goodsCount = Number(row.boxNum) * Number(row.boxUnitCount) + Number(row.mainNum)
        if (row.isGift == '1') {
          row.taxBoxPrice = 0
          row.noTaxPrice = 0
          row.noTaxBoxPrice = 0
          row.taxAmount = 0
          row.noTaxAmount = 0
          row.tax = 0
        } else {
          row.taxAmount = row.goodsCount * Number(row.taxPrice)
          row.noTaxAmount = row.goodsCount * Number(row.taxPrice)
        }
      } else if (type === 'mainNum') {
        if (Number(row.mainNum) >= Number(row.boxUnitCount)) {
          const boxCount = parseInt(Number(row.mainNum) / Number(row.boxUnitCount))
          const mainCount = Number(row.mainNum) % Number(row.boxUnitCount)
          row.boxNum += boxCount
          row.mainNum = mainCount
        }
        row.goodsCount = Number(row.boxNum) * Number(row.boxUnitCount) + Number(row.mainNum)
        if (row.isGift == '1') {
          row.taxBoxPrice = 0
          row.noTaxPrice = 0
          row.noTaxBoxPrice = 0
          row.taxAmount = 0
          row.noTaxAmount = 0
          row.tax = 0
        } else {
          row.taxAmount = row.goodsCount * Number(row.taxPrice)
          row.noTaxAmount = row.goodsCount * Number(row.taxPrice)
        }
      }
      row.billTaxAmount = row.goodsCount * Number(row.billTaxPrice)
      row.boxCount = Number(row.goodsCount) / Number(row.boxUnitCount).toFixed(6)
      this.giveCount = this.getGiftCount(row.isGift == 1)
    },
    columnLabel(obj) {
      if (obj.showName) {
        return obj.showName
      }
      obj.showName = obj.label
      return obj.showName
    },
    tabSave() {
      this.tableConfigShow01 = false
      this.toUpdateHeader()
      this.handleCancelSort()
    },
    sortTab(row) {
      if (row.column.order) {
        this.query.sort = `${row.column.property},${row.column.order === 'ascending' ? 'asc' : 'desc'}`
      } else {
        try {
          this.query.sort = null
        } catch (e) {
          console.err(e)
        }
      }
      this.onGet()
    },
    // 获取活动商品及赠品
    async setPromotionId(promotion) {
      this.showPromotionBox = false
      this.promotionId = promotion.promotionId
      this.promotionCode = promotion.promotionCode
      this.promotionName = promotion.promotionName
      const { content } = await giftPromotionDetail({ customerId: this.customerId, promotionId: this.promotionId })
      this.remark = content.promotionInfo.remark
      this.promotionName = content.promotionInfo.name
      this.ruleList = content.promotionInfo.detailList[0].ruleList
      const giftList = content.promotionInfo.detailList[0].giftList
      this.giftList = giftList.filter(item => item.isGift === 1)
      this.promotionGoodsList = giftList.filter(item => item.isGift === 0)
      for (const i in this.giftList) {
        const goodsTagId = this.giftList[i].goodsTagId
        const goodsTagName = this.giftList[i].goodsTagName
        this.$set(this.giftList, i, Object.assign({}, content.goodsList.find(val => this.giftList[i].goodsId === val.goodsId),
          { boxNum: 0, mainNum: 0, goodsCount: 0, taxAmount: 0, noTaxAmount: 0, taxPrice: 0, noTaxPrice: 0, taxBoxPrice: 0, noTaxBoxPrice: 0,
            oldTaxPrice: 0,
            oldNoTaxPrice: 0,
            oldTaxBoxPrice: 0,
            oldNoTaxBoxPrice: 0,
            oldTaxAmount: 0,
            oldNoTaxAmount: 0,
            oldTax: 0,
            isPromotionAdd: '1',
            promotionId: this.promotionId,
            promotionCode: this.promotionCode,
            promotionName: this.promotionName,
            goodsTagId: goodsTagId,
            goodsTagName: goodsTagName,
            isGift: '1',
            isGiftPaperBox: this.giftList[i].isGiftPaperBox
          }))
        console.log(this.giftList)
      }
      for (const i in this.promotionGoodsList) {
        this.$set(this.promotionGoodsList, i, Object.assign({}, content.goodsList.find(val => this.promotionGoodsList[i].goodsId === val.goodsId), {
          boxNum: 0, mainNum: 0, goodsCount: 0,
          isRequired: this.promotionGoodsList[i].isRequired,
          isPromotionAdd: '1',
          promotionId: this.promotionId,
          promotionCode: this.promotionCode,
          promotionName: this.promotionName,
          isGift: '0'
        }))
        const { billTaxPrice, billTaxBoxPrice, taxPrice, taxBoxPrice } = this.promotionGoodsList[i]
        this.promotionGoodsList[i].billTaxPrice = billTaxPrice || taxPrice
        this.promotionGoodsList[i].billTaxBoxPrice = billTaxBoxPrice || taxBoxPrice
      }
      if(this.promotionGoodsList.length === 1 && this.giftList.length === 1){
        if (this.ruleList[0].reachType === 3){
          this.$set(this.promotionGoodsList[0],'boxNum',this.ruleList[0].full)
          this.computedCount(this.promotionGoodsList[0],'boxNum')
        }else if (this.ruleList[0].reachType === 2){
          this.$set(this.promotionGoodsList[0],'mainNum',this.ruleList[0].full)
          this.computedCount(this.promotionGoodsList[0],'mainNum')
        }
      }
      this.promotionShow = true
    },
    getIndex(list, value) {
      for (let i = 0; i < list.length; i++) {
        if (list[i].goodsId === value) {
          return i
        }
      }
      return -1
    },
    keyDown() {
      if (!this.$parent.$parent.showQueryGoods) {
        return
      }
      let index
      try {
        var row = this.$refs.table.store.states.currentRow
        if (row.goodsId !== undefined) {
          index = this.getIndex(this.goodsList, row.goodsId)
        } else {
          index = -1
        }
      } catch (e) {
        index = -1
      }
      if (event.keyCode === 40) {
        event.preventDefault()
        this.$refs.table.setCurrentRow(this.goodsList[index + 1])
        var dom = this.$refs.table.bodyWrapper
        this.$nextTick(() => {
          dom.scrollTo(0, (index + 1) * 29)
        })
        this.$refs.ipt.blur()
        if (!this.showPromotionBox) {
          this.showPromotionBox = true
        }
        setTimeout(() => {
          this.promotionList = this.$refs.table.store.states.currentRow.giftPromotionInfoList || []
          this.giftList = []
          this.promotionGoodsList = []
        }
        , 10)
      } else if (event.keyCode === 38) {
        event.preventDefault()
        if (index > 0) {
          this.$refs.table.setCurrentRow(this.goodsList[index - 1])
          var dom = this.$refs.table.bodyWrapper
          this.$nextTick(() => {
            dom.scrollTo(0, (index - 1) * 29)
          })
          this.$refs.ipt.blur()
        } else {
          var dom = this.$refs.table.bodyWrapper
          this.$nextTick(() => {
            dom.scrollTo(0, index * 29)
          })
          this.$refs.table.setCurrentRow(null)
          this.$refs.ipt.focus()
        }
        if (!this.showPromotionBox) {
          this.showPromotionBox = true
        }
        setTimeout(() => {
          this.promotionList = this.$refs.table.store.states.currentRow.giftPromotionInfoList || []
          this.giftList = []
          this.promotionGoodsList = []
        }
        , 10)
      } else if (event.keyCode === 13) {
        if (this.$refs.ipt == document.activeElement) {
          this.queryGoods01()
          this.$refs.ipt.blur()
        } else {
          this.pushGoods()
        }
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.flex-row{
  display: flex;
  flex-direction: row;
}
.bottomBtn{
  display: flex;
  flex-direction: row-reverse;
  width: 30%;
  .btn_1{
    margin: 10px;
  }
}
.ipt{
  width: 100%;
  border: rgba(200,200,200,0.8) solid 1px;
}
.leftTableBox{
  width: 1600px
}
.rightTableBox{
  min-width: 700px;
  div{
    overflow: auto;
  }
}
.inputBox{
  border:rgba(203,203,203,0.6) 1px solid;
  input{
    border: none;
    outline:none;
    height: 30px;
    width: 70px;
    border-radius: 2px;
  }
}
.close{
  font-size: 36px;
  width: 100%;
  height: 40px;
  padding-right: 10px;
  cursor: pointer;
}
.suspensionBox{
  border: red 1px solid;
  background-color: #ffffff;
  width: 200px;
  height: 555px;
  position: absolute;
  z-index: 999;
  right: 15px;
  .title{
    height: 30px;
    font-size: 22px;
  }
  .promotion{
    padding-left: 20px;
    /*height: 30px;*/

    color: red;
    font-size: 18px;
    &:hover{
      background-color: rgba(203,203,203,0.6);
    }

  }
}
.tabBox{
  transition: width 0.6s linear;
}
.promotionType{

  width: 1200px;
  font-size: 20px;
  color: red;
  right: 0;
}
.promotionTypeName{
  width: 40px !important;
  height: 20px;
  border-radius: 5px;
  border: red solid 1px;
  color: red;
  display: inline-block;
}
</style>
